import React, { useState,useEffect } from "react";
import { NavBar, Form, Input, Button ,Checkbox,Dialog,Toast} from "antd-mobile";
import style from "./index.module.css";
import axios from "../../utils/request";
import { useNavigate } from "react-router-dom";

function Login() {
  const [obj, setObj] =useState({})
  const [checkedItem, setCheckedItem] = useState(false)
  const formRef= React.createRef()
  const navigate = useNavigate();
  const onFinish =async (values) => {
    // console.log(values);
    if(!checkedItem){
      Toast.show({
        icon: 'fail',
        content: '请勾选用户协议',
      })
      return;
    }
    let res=await axios.post("/api/login", {
      username: values.username,
      password: '123456',
    })
    // console.log(res);
    if(res.status==200&&res.data.code==10000){
      // (1)实现账号登录效果,使用localstorage进行本地存储token值
      setObj(res.data.data)
      // (1)使用useState管理用户信息
      localStorage.setItem('accessToken',res.data.data.accessToken)
      localStorage.setItem('refreshToken',res.data.data.refreshToken)
      localStorage.setItem('username',res.data.data.userInfo.username)
      localStorage.setItem('avator',res.data.data.userInfo.avator)
      Toast.show({
        icon: 'success',
        content: '登录成功',
      })
      navigate('/')
    }

  };

  const handleRead=()=>{
    setCheckedItem(true)
  }
  const handleChange=(e)=>{
    console.log(e);
  }
  return (
    <div>
      <NavBar>登录</NavBar>
      <div className={style["login_top"]}>
        <h1>手机动态密码登录</h1>
        <p>未注册手机登录后即可完成注册</p>
      </div>
      <Form
        ref={formRef}
        layout="vertical"
        onFinish={onFinish}
        initialValues={{
          mobile: { preValue: "86", realValue: "" },
        }}
        footer={
          <Button block type="submit" color="primary" size="large">
            提交
          </Button>
        }
      >
        <Form.Item 
        name="username" 
        label="手机号" 
        rules={[{ required: true ,message: '手机号不能为空' },
          // (2)使用正则表达式进行账号校验,账号要求手机号验证
          {pattern: /^1[3|5|7|9|8]\d{9}$/,message: '请输入正确的手机号'}
        ]}>
          <Input placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item name='b' required >
        <Checkbox value='1' onChange={(e)=>handleChange(e)} checked={checkedItem}>
        {/* (1)点击"阅读协议"弹出协议内容,选择后才可以登陆 */}
            <Button
            style={{border: 'none'}}
            block
            onClick={() =>
              Dialog.alert({
                content: '协议内容',
                onConfirm: () => handleRead(),
              })
            }
          >
           阅读协议
          </Button>
          </Checkbox>
        </Form.Item>
      </Form>
    </div>
  );
}

export default Login;
